<?php
/**
 * Created by PhpStorm.
 * User: DD
 * Date: 2016/4/22
 * Time: 1:05
 */

namespace app\common\util;


class FileUploader
{
    private static $ext_arr = array(
        'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
        'flash' => array('swf', 'flv'),
        'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
        'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
    );
    private $_save_path;
    private $_max_size = 100000000;
    private $_save_url;
    private $_error;
    private $_options;
    private $_filesize;
    private $_filename;
    private $_oriName;

    public function __construct($options = [])
    {
        $this->_options = array_merge([
            'fileType' => 'image'
        ], $options);
        $this->_save_path = realpath(APP_PATH . '../public/static/upload') . '/';
//        $this->_save_path = '/home/sites/images/img.9kk.com/';
        $this->_save_url = '/static/upload/';
    }

    private function _checkError()
    {
        if (!empty($_FILES['_file_']['error'])) {
            switch ($_FILES['_file_']['error']) {
                case '1':
                    $error = '超过php.ini允许的大小。';
                    break;
                case '2':
                    $error = '超过表单允许的大小。';
                    break;
                case '3':
                    $error = '图片只有部分被上传。';
                    break;
                case '4':
                    $error = '请选择图片。';
                    break;
                case '6':
                    $error = '找不到临时目录。';
                    break;
                case '7':
                    $error = '写文件到硬盘出错。';
                    break;
                case '8':
                    $error = 'File upload stopped by extension。';
                    break;
                case '999':
                default:
                    $error = '未知错误。';
            }
            $this->_error = $error;
        }
        return $this->_error;
    }

    public function getUploadedFile()
    {
        $error = $this->_checkError();
        if (!$error) {
            do {
                if (empty($_FILES) === false) {
                    //原文件名
                    $this->_oriName = $file_name = $_FILES['_file_']['name'];
                    //服务器上临时文件名
                    $tmp_name = $_FILES['_file_']['tmp_name'];
                    //文件大小
                    $this->_filesize = $file_size = $_FILES['_file_']['size'];

                    //检查文件名
                    if (!$file_name) {
                        $this->_error = "请选择文件";
                        break;
                    }

                    //检查是否已上传
                    if (@is_uploaded_file($tmp_name) === false) {
                        $this->_error = "上传失败";
                        break;
                    }
                    //检查文件大小
                    if ($file_size > $this->_max_size) {
                        $this->_error = "上传文件大小超过限制";
                        break;
                    }
                    //检查目录名
                    $dir_name = $this->_options['fileType'];
                    if (empty(self::$ext_arr[$dir_name])) {
                        $this->_error = "文件类型不支持";
                        break;
                    }
                    //获得文件扩展名
                    $temp_arr = explode(".", $file_name);
                    $file_ext = array_pop($temp_arr);
                    $file_ext = trim($file_ext);
                    $file_ext = strtolower($file_ext);
                    //检查扩展名
                    if (in_array($file_ext, self::$ext_arr[$dir_name]) === false) {
                        $this->_error = "上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", self::$ext_arr[$dir_name]) . "格式";
                        break;
                    }
                    //新文件名
                    $size = getimagesize($tmp_name);
                    $this->_filename = $new_file_name = md5(uniqid(rand()) . rand(10000, 99999)) . '_' . $size[0] . 'x' . $size[1] . '.' . $file_ext;
                    $this->_save_path = $dir_name . '/' . $new_file_name;
                    return $tmp_name;
                } else {
                    $this->_error = '请上传文件';
                }
            } while (0);
        }
        return false;
    }

    public function saveFile()
    {
        $error = $this->_checkError();
        if (!$error) {
            if (empty($_FILES) === false) {
                //原文件名
                $this->_oriName = $file_name = $_FILES['_file_']['name'];
                //服务器上临时文件名
                $tmp_name = $_FILES['_file_']['tmp_name'];
                //文件大小
                $this->_filesize = $file_size = $_FILES['_file_']['size'];
                //检查文件名
                if (!$file_name) {
                    return $this->_error = "请选择文件";
                }
                //检查目录
                if (@is_dir($this->_save_path) === false) {
                    return $this->_error = "上传目录不存在";
                }
                //检查目录写权限
                if (@is_writable($this->_save_path) === false) {
                    return $this->_error = $this->_save_path."上传目录没有写权限";
                }
                //检查是否已上传
                if (@is_uploaded_file($tmp_name) === false) {
                    return $this->_error = "上传失败";
                }
                //检查文件大小
                if ($file_size > $this->_max_size) {
                    return $this->_error = "上传文件大小超过限制";
                }
                //检查目录名
                $dir_name = $this->_options['fileType'];
                if (empty(self::$ext_arr[$dir_name])) {
                    return $this->_error = "目录名不正确";
                }
                //获得文件扩展名
                $temp_arr = explode(".", $file_name);
                $file_ext = array_pop($temp_arr);
                $file_ext = trim($file_ext);
                $file_ext = strtolower($file_ext);
                //检查扩展名
                if (in_array($file_ext, self::$ext_arr[$dir_name]) === false) {
                    return $this->_error = "上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", self::$ext_arr[$dir_name]) . "格式";
                }
                //创建文件夹
                if ($dir_name !== '') {
                    $this->_save_path .= $dir_name . "/";
                    $this->_save_url .= $dir_name . "/";
                    if (!file_exists($this->_save_path)) {
                        @mkdir($this->_save_path, 0777, true);
                        @chmod($this->_save_path, 0777);
                    }
                }
                $ymd = date("Ymd");
                $this->_save_path .= $ymd . "/";
                $this->_save_url .= $ymd . "/";
                if (!file_exists($this->_save_path)) {
                    mkdir($this->_save_path, 0777, true);
                    @chmod($this->_save_path, 0777);
                }
                //新文件名
                $this->_filename = $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
                //移动文件
                $file_path = $this->_save_path . $new_file_name;

                if (move_uploaded_file($tmp_name, $file_path) === false) {
                    return $this->_error = "上传文件失败";
                }
                @chmod($file_path, 0644);
                $this->_save_url = $this->_save_url . $new_file_name;
                return false;
            }
        }
        return $error;
    }

    public function getUploadFileUrl()
    {
        return $this->_save_url;
    }

    public function getError()
    {
        return $this->_error;
    }

    public function getFileSavePath()
    {
        return $this->_save_path;
    }

    public function getFileExt()
    {
        return strtolower(strrchr($this->_oriName, '.'));
    }

    public function getOriName()
    {
        return $this->_oriName;
    }

    public function getFileName()
    {
        return $this->_filename;
    }

    public function getFileSize()
    {
        return $this->_filesize;
    }


}